package com.yushu.authority.controller;


import com.yushu.authority.pojo.bo.PmUser;
import com.yushu.authority.pojo.vo.PmUserVO;
import com.yushu.authority.service.PmUserService;
import com.yushu.common.anno.LogAop;
import com.yushu.common.execption.CgException;
import com.yushu.common.util.pager.Pages;
import com.yushu.common.util.result.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.mail.imap.protocol.ID;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


 /**
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
//@Api(description = "用户管理")
@RestController
@RequestMapping("/authority/pmUser")
public class PmUserController {
   private Logger logger = Logger.getLogger(PmUserController.class);

    @Autowired
    private PmUserService pmUserService;
    private Map<String, Object> resultMap;

	 @Autowired
     HttpServletRequest request;

     @Autowired
     RedisTemplate redisTemplate;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }

    /**
     * 分页条件查询用户数据
     * 2020-01-16 19:58:01
     *
     * @param tablePage
     * @return
     */
    @LogAop("分页查询用户")
    @ResponseBody
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public Pages page(@RequestBody Pages<PmUserVO> tablePage) {
        Pages page = pmUserService.page(tablePage);
        return page;
    }

    /**
     * 查询全部用户数据
     * 2020-01-16 19:58:01
     */
    @ResponseBody
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    public List<PmUser> queryList(@RequestBody PmUser pmUser) {
        List<PmUser> list = pmUserService.selectList(pmUser);
        return list;
    }


    /**
     * 添加或者更新用户
     * 2020-01-16 19:58:01
     * 2019-07-24 10:30:15
     * 2019-12-31 10:33:53
     *
     * @param pmUser
     * @return
     */
    @LogAop("新增用户")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(@RequestBody PmUser pmUser) {
        try {
            logger.info("进入添加用户方法");
            pmUserService.insert(pmUser);
            return Result.success("用户新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    
    @LogAop("编辑用户")
    @RequestMapping(value = "/editor", method = RequestMethod.POST)
    @ResponseBody
    public Result editor(@RequestBody PmUser pmUser) {
        try {
            logger.info("进入修改用户方法");
            pmUserService.updateByKey(pmUser);
            return Result.success("用户修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }


    /**
     * 批量删除用户数据
     * 2020-01-16 19:58:01
     *
     * @param pmUsers 用户集合
     */
    @LogAop("批量删除用户")
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public Result batchDelete(Model model, @RequestBody List<PmUser> pmUsers) {
        logger.info("进入到删除用户数据方法");
        try {
            pmUserService.deleteBatch(pmUsers);
            return Result.success("批量删除用户成功");
        } catch (CgException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());

        }
    }

//
//    /**
//     * 跳转用户列表页面
//     * 2020-01-16 19:58:01
//     */
//    @RequestMapping(value = "toPmUserList", method = RequestMethod.GET)
//    public String toPmUserList(Model model) {
//        model.addAttribute("title", "用户管理");
//        model.addAttribute("page", "/authority/pmUser/list");
//        return "menuPage";
//    }
//
//    /**
//     * 跳转用户跳转到空白列表页面
//     * 2020-01-16 19:58:01
//     */
//    @RequestMapping(value = "toOpenPmUserList", method = RequestMethod.GET)
//    public String toOpenPmUserList(Model model, HttpServletRequest request) {
//        model.addAttribute("title", "用户管理");
//        model.addAttribute("page", "/authority/pmUser/list");
//        return "openPage";
//    }
//
//    /**
//     * 跳转用户新增或修改页面
//     * 2019-07-24 10:30:15
//     * 2020-01-16 19:58:01
//     */
//    @RequestMapping(value = "toEditor", method = RequestMethod.GET)
//    public String toEditor(Model model, String id, HttpServletRequest request) {
//        if (StringUtils.isNotEmpty(id)) {
//            request.setAttribute("data", pmUserService.queryPmUserByKey(id));
//        }
//        model.addAttribute("title", "用户管理");
//        model.addAttribute("page", "/authority/pmUser/addUpdate");
//        return "openPage";
//    }


    @RequestMapping("checkRepeat")
    @ResponseBody
    public String checkRepeat(@RequestBody Map map) {
        return pmUserService.checkRepeat(map);
    }


    /**
     * 删除用户数据
     * 2020-01-16 19:58:01
     *
     * @param pmUser 需要删除的对象
     */
    @LogAop("删除用户")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result delete(Model model, @RequestBody PmUser pmUser) {
        try {
            pmUserService.deleteById(pmUser.getId());
            logger.info("删除用户成功");
            return Result.success("删除用户成功");
        } catch (CgException e) {
            logger.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }
//
//    /**
//     * 跳转权限用户表列表页面
//     * 2019-12-31 10:33:53
//     */
//    @RequestMapping(value = "toUserList", method = RequestMethod.GET)
//    public String toUserList(Model model) {
//        model.addAttribute("title", "权限用户表管理");
//        model.addAttribute("page", "/authority/pmUser/list");
//        return "menuPage";
//    }


//    /**
//     * 如果有角色被用户关联则角色不允许被删除，如果有用户关联角色，则用户也不允许被删除
//     * 跳转权限用户表跳转到空白列表页面
//     * 2019-12-31 10:33:53
//     */
//    @RequestMapping(value = "toOpenUserList", method = RequestMethod.GET)
//    public String toOpenUserList(Model model, HttpServletRequest request) {
//        model.addAttribute("title", "权限用户表管理");
//        model.addAttribute("page", "/authority/pmUser/list");
//        return "openPage";
//    }


//    /**
//     * 跳转到分配角色页面
//     * 2019-07-24 10:30:15
//     */
//    @RequestMapping(value = "toAssignRoles", method = RequestMethod.GET)
//    public String toAssignRoles(Model model, HttpServletRequest request) {
//        model.addAttribute("title", "分配角色");
//        model.addAttribute("page", "/authority/pmUser/assignRoles");
//        return "openPage";
//    }


    /**
     * 验证用户名是否存在
     * 2019-7-24 14:21:26
     */
    @ResponseBody
    @RequestMapping(value = "/validateUserName", method = RequestMethod.POST)
    public String validateUserName(@RequestBody String userName,String key) {
 		PmUser pmUser = new PmUser();
        pmUser.setUserName(userName);
        try {
            PmUser pmUser1 = pmUserService.validateUserName2(pmUser);
            if (pmUser1 == null) {
                return "success";
            } else {
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
       
    }

    /**
     * 验证email是否存在
     * 2019-7-24 14:21:26
     */
     
    @ResponseBody
    @RequestMapping(value = "/validateEmail", method = RequestMethod.POST)
    public String validateEmail(@RequestBody String userEmail) {
        PmUser pmUser = pmUserService.wUserEmail(userEmail);
        if (pmUser == null) {
            return "success";
        } else {
            return "error";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/validateUserTel", method = RequestMethod.POST)
    public String validateUserTel(String userTel,String key) {
        try {
            return pmUserService.validateUserTel(userTel, key);
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
    
    
      /**
     * 验证旧密码是否正确
     */

   @ResponseBody
    @RequestMapping(value = "/validateOldPassword", method = RequestMethod.POST)
    public boolean forgotPassword(String oldPassword,String key) {

        PmUser pmUser = new PmUser();
        pmUser.setUserName(key);

        PmUser pmUserValue = pmUserService.validateUserName2(pmUser);

        SimpleHash sh = new SimpleHash("MD5",oldPassword, pmUserValue.getUserName(), 1);

        PmUser pmUser1 = pmUserService.queryoldPassword(oldPassword, key);

        //验证输入的密码是否和数据库中的密码一样
        if(!sh.toString().equals(pmUser1.getPassword())){
            return false;
        }else {
            return true;
        }
      }

     //修改密码
    @ResponseBody
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public int changePassword(PmUserVO pmUserVO, HttpServletRequest request) {
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        String key = request.getParameter("key");
        PmUser pmUserName = new PmUser();
        pmUserName.setUserName(key);
        PmUser pmUser = pmUserService.validateUserName2(pmUserName);
        //加密原密码
        SimpleHash sh = new SimpleHash("MD5",oldPassword, pmUser.getUserName(), 1);
        //加密新密码
        SimpleHash newSh = new SimpleHash("MD5",confirmPassword, pmUser.getUserName(), 1);
        pmUserVO.setOldPassword(sh.toString());
        pmUserVO.setNewPassword(newPassword);
        pmUserVO.setConfirmPassword(newSh.toString());
        return pmUserService.changePassword(pmUserVO);
    }
    
    /*修改忘记密码*/

    @ResponseBody
    @RequestMapping(value = "/changeForgetPassword",method = RequestMethod.POST)
    public boolean fPssword(HttpServletRequest request,PmUserVO pmUserVO){
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        String userEmail = request.getParameter("userEmail");
        PmUser pmUser = pmUserService.wUserEmail(userEmail);
        //加密新密码
        SimpleHash shNew = new SimpleHash("MD5",confirmPassword, pmUser.getUserName(), 1);
        pmUserVO.setNewPassword(newPassword);
        pmUserVO.setConfirmPassword(shNew.toString());
       return pmUserService.changeForgetPassword(pmUserVO);
    }
    
    
    //邮箱验证码
    String code = null;
    //校验邮箱是否存在
    @ResponseBody
    @RequestMapping(value = "/validateQueryEmail", method = RequestMethod.GET)
    public boolean queryEmail(HttpServletRequest request,String userEmail) {

        System.out.println(userEmail);
        Map<String, Object> map = pmUserService.queryEmail(userEmail);
        String count = (String) map.get("count");
        //获取redis里面保存的验证码
        code = (String) map.get("code");
//        System.out.println("code  "+code);
        if (count.equals("1")) {
            return true;
        } else {
            return false;
        }
    }

    //用户注册

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public boolean register(@RequestBody PmUser pmUser, HttpServletRequest request) {
//        String userEmail = request.getParameter("userEmail");
//        String userName = request.getParameter("userName");
//        String password = request.getParameter("password");
//        if(!userEmail.equals("") && !userName.equals("") && !password.equals("")){
//            pmUser.setUserEmail(userEmail);
//            pmUser.setUserName(userName);
//            pmUser.setPassword(password);
//        }

        return pmUserService.register(pmUser);
    }

    //找回密码
    @ResponseBody
    @RequestMapping(value = "/validateCode", method = RequestMethod.POST)
    public boolean backPassword(HttpServletRequest request) {
        String pcode = request.getParameter("code");
        if (code.equals(pcode)) {
            return true;
        } else {
            return false;
        }
    }
    
    //验证用户名是否存在
     @ResponseBody
     @RequestMapping(value = "/validateUname",method = RequestMethod.POST)
     public String validateUname(String userName, String key){
         try {
             return pmUserService.validateUserName(userName,key);
         }catch (Exception e){
             e.printStackTrace();
             return "false";
         }
     }
    
}

